/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.entity;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Query;
import javax.persistence.Table;

@Entity
@Table(name = Constants.TABLE_NAME_PREFIX + "application")
@NamedQueries({
		@NamedQuery(name = ApplicationEntity.QUERY_NAME, query = "SELECT app FROM ApplicationEntity AS app WHERE app.name = :name"),
		@NamedQuery(name = ApplicationEntity.QUERY_ALL, query = "SELECT app FROM ApplicationEntity AS app") })
public class ApplicationEntity implements Serializable {

	private static final long serialVersionUID = 1L;

	public static final String QUERY_NAME = "ae.name";

	public static final String QUERY_ALL = "ae.all";

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(unique = true)
	private String name;

	public ApplicationEntity() {
		super();
	}

	public ApplicationEntity(String name) {
		this.name = name;
	}

	public long getId() {
		return this.id;
	}

	public String getName() {
		return this.name;
	}

	public static boolean hasApplication(EntityManager entityManager,
			String name) {
		Query query = entityManager.createNamedQuery(QUERY_NAME);
		query.setParameter("name", name);
		List<ApplicationEntity> resultList = query.getResultList();
		return !resultList.isEmpty();
	}

	public static List<ApplicationEntity> getApplications(
			EntityManager entityManager) {
		Query query = entityManager.createNamedQuery(QUERY_ALL);
		return query.getResultList();
	}
}
